import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:live_bg_mobile/common/const/app_color_const.dart';

import '../../common/api/site_api.dart';
import '../../common/const/app_style_const.dart';
import '../../common/enum/btn_enum.dart';
import '../../common/type/data_list_container_type.dart';
import '../../common/util/common_util.dart';
import '../../widget/card_container.dart';
import '../../widget/data_list_container.dart';
import '../../widget/error_img.dart';
import '../../widget/form_item.dart';
import '../../widget/gradient_btn.dart';
import '../../widget/ripple_card_container.dart';

class SiteManagementPage extends StatefulWidget {
  const SiteManagementPage({Key? key}) : super(key: key);

  @override
  State<SiteManagementPage> createState() => SiteManagementPageState();
}

class SiteManagementPageState extends State<SiteManagementPage> {
  GlobalKey<DataListContainerState> dataListContainerStateKey =
      GlobalKey<DataListContainerState>();

  @override
  void initState() {
    super.initState();
  }

  getData(DataListContainerQueryParam param) {
    return SiteApi.getLocList(
        {"status": 0, "limit": param.pageSize, "page": param.currentPage});
  }

  upOrDown(Map data) {
    SiteApi.upOrDown(data).then((res) {
      if (null != res.data && res.data["isSuccess"]) {
        CommonUtil.showToast(data['status'] == 1 ? '上架成功！' : '下架成功！');
        dataListContainerStateKey.currentState!.refresh();
      } else {
        CommonUtil.showToast(res.data["msg"]);
      }
    });
  }

  upOrDownSite(Map item) {
    if (item['status'] == 1) {
      CommonUtil.showSingleConfirmDialog(
          "upOrDownSiteConfirmDialog", 160, "您确认要下架“${item['name']}“吗？", (cb) {
        cb();
        upOrDown({"id": item["id"], "status": 2});
      });
    } else {
      upOrDown({"id": item["id"], "status": 1});
    }
  }

  Widget buildTitle(context, item) {
    return LayoutBuilder(builder: (buildCtx, constraints) {
      return Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [
        SizedBox(
          width: constraints.maxWidth / 2 + 40,
          child: Text(
            CommonUtil.valueEmptyToDefStr(item["name"]),
            style: cardContainerNormalTitleStyle,
            overflow: TextOverflow.ellipsis,
          ),
        ),
        Row(
          mainAxisAlignment: MainAxisAlignment.end,
          children: [
            item["status"] == 1
                ? GradientBtn(
                    onTap: () => {upOrDownSite(item)},
                    label: "下架",
                    gradientBtnType: GradientBtnType.red)
                : GradientBtn(
                    onTap: () => {upOrDownSite(item)},
                    label: "上架",
                    gradientBtnType: GradientBtnType.green,
                  ),
            Container(
              padding: const EdgeInsets.only(right: 0.0, left: 10.0),
              child: GradientBtn(
                  label: "详情",
                  onTap: () {
                    Navigator.of(context).pushNamed("/siteDetail",
                        arguments: {"id": item['id']});
                  }),
            )
          ],
        )
      ]);
    });
  }

  Widget listBodyBuilder(context, item) {
    String img = '';
    if (item["locPicList"].isEmpty) {
      img = '';
    } else {
      img = item['locPicList'][0];
    }
    return CardContainer(
        margin: const EdgeInsets.only(bottom: 10.0),
        titleBuilder: (context) => buildTitle(context, item),
        bodyPadding: const EdgeInsets.all(12.0),
        bodyBuilder: (c) => Container(
              color: lightGrayColor8,
              padding: const EdgeInsets.all(8.0),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.start,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  RippleCardContainer(
                      width: 60,
                      height: 50,
                      onTap: () {
                        CommonUtil.showImgViewer(context, 0, [img]);
                      },
                      child: img.isNotEmpty
                          ? Image.network(
                              img,
                              errorBuilder: (BuildContext context, Object error,
                                      StackTrace? stackTrace) =>
                                  const ErrorImg(),
                            )
                          : const ErrorImg()),
                  Expanded(
                      child: Padding(
                    padding: const EdgeInsets.only(left: 10.0),
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.start,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        LayoutBuilder(builder: (buildContext, constraints) {
                          return FormItem(
                            padding: const EdgeInsets.only(bottom: 6.0),
                            label: '联系电话',
                            crossAxisAlignment: CrossAxisAlignment.start,
                            valueWidth: constraints.maxWidth - 70,
                            value: CommonUtil.valueEmptyToDefStr(
                                item["contactTel"]),
                          );
                        }),
                        LayoutBuilder(builder: (buildContext, constraints) {
                          return FormItem(
                            label: '详细地址',
                            crossAxisAlignment: CrossAxisAlignment.start,
                            valueWidth: constraints.maxWidth - 70,
                            valueOverflow: TextOverflow.ellipsis,
                            value: CommonUtil.valueEmptyToDefStr(
                                item["fullAddressInfo"]),
                          );
                        })
                      ],
                    ),
                  ))
                ],
              ),
            ));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text("基地管理"),
          actions: [
            Padding(
              padding: const EdgeInsets.only(right: 2.0),
              child: IconButton(
                icon: const Icon(
                  Icons.add,
                  size: 25,
                ),
                onPressed: () {
                  Navigator.of(context)
                      .pushNamed("/siteAdd", arguments: {"id": ""});
                },
              ),
            ),
          ],
        ),
        body: DataListContainer(
          key: dataListContainerStateKey,
          getData: getData,
          listBodyBuilder: listBodyBuilder,
        ));
  }
}
